<template>
  <div id="addAppPage" class="container">
    <!-- 标题区域 -->
    <div class="header">
      <h2 class="title">📊 添加可视化图表</h2>
      <p class="subtitle">通过上传数据文件快速生成可视化分析</p>
    </div>

    <!-- 表单区域 -->
    <a-form
      :model="form"
      class="custom-form"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <!-- 分析目标 -->
      <a-form-item field="goal" label="分析目标" required>
        <a-input
          v-model="form.goal"
          placeholder="例：分析网站用户的增长趋势和地域分布特征"
          class="rounded-input"
        />
      </a-form-item>

      <!-- 图表名称 -->
      <a-form-item field="name" label="图表名称" required>
        <a-input
          v-model="form.name"
          placeholder="请输入图表展示名称（例：用户增长趋势分析）"
          class="rounded-input"
        />
      </a-form-item>

      <!-- 图表类型选择 -->
      <a-form-item field="chartType" label="图表类型" required>
        <a-select
          v-model="form.chartType"
          placeholder="请选择最适合呈现您数据的图表类型"
          class="rounded-select"
        >
          <a-option
            v-for="(value, key) of charts_TYPE_MAP"
            :key="key"
            :value="value"
            :label="value"
          />
        </a-select>
      </a-form-item>

      <!-- 文件上传 -->
      <a-form-item label="数据上传" required>
        <a-upload
          :custom-request="handleFileUpload"
          :before-upload="beforeUpload"
          :limit="1"
          accept=".xlsx,.xls"
          class="upload-wrapper"
        >
          <template #upload-button>
            <div class="upload-card" :class="{ active: file }">
              <icon-upload class="upload-icon" />
              <div class="upload-text">
                {{ file ? file.name : "点击上传 CSV/Excel 文件" }}
              </div>
              <div class="upload-hint">支持扩展名：.xlsx .xls</div>
            </div>
          </template>
        </a-upload>
      </a-form-item>

      <!-- 提交按钮 -->
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          class="submit-btn"
          :loading="loading"
        >
          <template #icon>
            <icon-rocket v-if="!loading" />
          </template>
          {{ loading ? "分析中..." : "开始智能分析" }}
        </a-button>
      </a-form-item>
    </a-form>

    <!-- 结果展示区域 -->
    <div v-if="chart" class="result-section">
      <a-card class="result-card">
        <h3 class="result-title">📈 分析结论</h3>
        <div class="result-content">{{ chart.genResult }}</div>
      </a-card>
    </div>
    <h3 class="chart-title">✨ 生成图表预览</h3>
    <v-chart :option="vchart" style="height: 300px" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { charts_TYPE_MAP } from "@/constant/app";
import { genChartByAiUsingPost } from "@/api/chartController";
import VChart from "vue-echarts";
import "echarts";
import API from "@/api";

const router = useRouter();

// 表单数据
const form = ref({
  goal: "",
  name: "",
  chartType: "",
});

const chart = ref<API.BiResponse | undefined>(undefined);
const option = ref<any>(undefined);
const loading = ref(false);

// 文件
const file = ref<File | null>(null);

/**
 * 文件上传前的验证
 */
const beforeUpload = (file: File) => {
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  if (!isExcel) {
    Message.error("只能上传 Excel 文件");
    return false;
  }
  return true;
};

/**
 * 文件上传逻辑
 */
const handleFileUpload = (options: any) => {
  const { fileItem } = options;
  file.value = fileItem.file;
  Message.success("文件上传成功");
};

/**
 * 表单提交逻辑
 */
const handleSubmit = async () => {
  if (!form.value.goal || !form.value.name || !form.value.chartType) {
    Message.error("请填写所有必填项");
    return;
  }

  if (!file.value) {
    Message.error("请上传文件");
    return;
  }

  loading.value = true;

  try {
    const res: any = await genChartByAiUsingPost(
      { ...form.value },
      {},
      file.value
    );
    if (res.data.code === 0 && res.data.data) {
      Message.success("分析成功");
      chart.value = res.data.data;

      // 将 genChart 字符串解析为 JavaScript 对象
      try {
        option.value = JSON.parse(chart.value?.genChart || "{}");
      } catch (e) {
        console.error("解析图表数据失败：", e);
        Message.error("图表数据格式错误");
        option.value = {};
      }
    } else {
      Message.error("分析失败，" + res.data.message || "");
    }
  } catch (e: any) {
    Message.error("添加失败，" + e.message);
  } finally {
    loading.value = false;
  }
};

/**
 * 图表配置
 */
const vchart = computed(() => {
  return option.value;
});
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 24px;
}

.header {
  text-align: center;
  margin-bottom: 48px;
}

.title {
  font-size: 28px;
  color: #1f2d3d;
  margin-bottom: 8px;
}

.subtitle {
  color: #99a9bf;
  font-size: 14px;
}

.custom-form {
  background: #fff;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 输入框样式 */
:deep(.rounded-input .arco-input) {
  border-radius: 8px;
  padding: 12px 16px;
  transition: all 0.3s;
}

:deep(.rounded-input .arco-input:hover) {
  border-color: #3491fa;
}

/* 下拉选择样式 */
:deep(.rounded-select .arco-select-view) {
  border-radius: 8px;
  padding: 12px 16px;
}

/* 上传组件样式 */
.upload-card {
  border: 2px dashed #e5e9f2;
  border-radius: 8px;
  padding: 32px 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-card.active {
  border-color: #3491fa;
  background-color: #f8faff;
}

.upload-icon {
  font-size: 28px;
  color: #99a9bf;
  margin-bottom: 12px;
}

.upload-text {
  color: #1f2d3d;
  font-weight: 500;
}

.upload-hint {
  color: #99a9bf;
  font-size: 12px;
  margin-top: 8px;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s;
}

/* 结果展示 */
.result-section {
  margin-top: 32px;
}

.result-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.result-title {
  color: #1f2d3d;
  margin-bottom: 16px;
}

.result-content {
  line-height: 1.8;
  color: #5e6d82;
}

.chart-title {
  margin-bottom: 24px;
  color: #1f2d3d;
}
</style>
